package com.dlc.felear.xiaoensale.utils;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.TypeReference;
import com.dlc.felear.xiaoensale.activity.CookingActivity;
import com.dlc.felear.xiaoensale.constant.Constant;
import com.dlc.felear.xiaoensale.dao.CookingMenuDao;
import com.dlc.felear.xiaoensale.dao.MenuFoodMaterialDao;
import com.dlc.felear.xiaoensale.dao.OperatorDao;
import com.dlc.felear.xiaoensale.entity.CookingMenu;
import com.dlc.felear.xiaoensale.entity.DeviceInfo;
import com.dlc.felear.xiaoensale.entity.MenuFoodMaterial;
import com.dlc.felear.xiaoensale.entity.Operator;
import com.dlc.felear.xiaoensale.entity.QueryMsgInfo;
import com.dlc.felear.xiaoensale.helper.JsonHelper;
import com.dlc.felear.xiaoensale.helper.OkHttpManager;
import com.dlc.felear.xiaoensale.helper.SendData;
import com.itdlc.android.library.utils.APPDidUtil;
import com.zhy.http.okhttp.callback.StringCallback;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class HandleSocketDataUtil {
    private static final String TAG = "HandleSocketDataUtil";
    private static HandleSocketDataUtil handleSocketDataUtil;
    private Context context;
    private CookingMenuDao cookingMenuDao;
    private OperatorDao operatorDao;
    private MenuFoodMaterialDao foodMaterialDao;
    private Map<String, StringBuffer> cacheStr = new HashMap<>();
    private boolean isCooking = false;
    private boolean cookingPage = false;
    private Map<String, CookingMenu> cacheMenus = new HashMap<>();
    private Map<String, DeviceInfo> devicesMap = new HashMap<>();
    private String bJDeviceId;


    private HandleSocketDataUtil(Context context) {
        log("HandleSocketDataUtil");
        this.context = context;
        cookingMenuDao = new CookingMenuDao(context);
        operatorDao = new OperatorDao(context);
        foodMaterialDao = new MenuFoodMaterialDao(context);
        bJDeviceId = APPDidUtil.getAppDid();
        queryData();
    }

    public void setCookingStatus(boolean flag) {
        isCooking = flag;
    }

    public void setcookingPageStatus(boolean flag) {
        cookingPage = flag;
    }

    public static HandleSocketDataUtil getInstance(Context context) {
        if (handleSocketDataUtil == null) {
            synchronized (HandleSocketDataUtil.class) {
                if (handleSocketDataUtil == null) {
                    handleSocketDataUtil = new HandleSocketDataUtil(context);
                }
            }
        }
        return handleSocketDataUtil;
    }

    public void recieveData(HashMap<String, Object> map) {
        log("接收的菜谱信息:" + JsonHelper.toJson(map));
        if (map != null && map.containsKey("option")) {
            switch ((int) map.get("option")) {
                case 0:
                    EventBus.getDefault().post((String) map.get("data"), Constant.SHOW_MSG_FOR_DIALOG);
                    showMsg((String) map.get("data"));
                    break;
                case 1:
                    menuCookingInfo((Map<String, Object>) map.get("data"));
                    break;
                case 11:
                case 12:
                    saveMenuInfo((Map<String, Object>) map.get("data"));
                    break;
                case 13:
                    updateMenuInfo((Map<String, Object>) map.get("data"));
                    break;
                case 101:
                    saveOperator((Map<String, Object>) map.get("data"));
                    break;
            }
        } else {
            showMsg("数据格式不符");
        }
    }

    private void saveOperator(Map<String, Object> info) {
        try {
            log("接收的炒菜步骤信息:" + JsonHelper.toJson(info));
            log("接收的炒菜步骤信息1:" + JsonHelper.toJson(info.get("operator")));
//            operatorDao.addAll((List<Operator>) info.get("operator"));
        } catch (Exception e) {
            log(e.getMessage());
        }
    }

    private void saveMenuOperator(String json, String id) {
        try {
            log("operators json:" + json);
            List<Operator> list = JsonHelper.parserJson(json, new TypeReference<List<Operator>>() {
            });
            log("operators:" + JsonHelper.toJson(list));
            if (list != null) {
                operatorDao.addAll(list, id);
            }
        } catch (Exception e) {
            log(e.getMessage());
        }
    }

    private void saveMenuInfo(Map<String, Object> info) {
        try {
            log("接收的菜谱信息:" + JsonHelper.toJson(info));
            CookingMenu cookingMenu = JsonHelper.parserJson(JsonHelper.toJson(info), CookingMenu.class);
            CookingMenu temp = cookingMenuDao.queryById(cookingMenu.getId());
            if (temp != null) {
                log("菜谱已经存在");
                return;
            }
            saveFoodMaterial(cookingMenu.getFoodMaterials());
            cookingMenuDao.createOrUpdate(cookingMenu);
            log("cookingMenu:" + JsonHelper.toJson(cookingMenu));
        } catch (Exception e) {
            log(e.getMessage());
        }
    }

    private void updateMenuInfo(Map<String, Object> info) {
        try {
            log("接收到推送来的更新菜谱的信息:" + JsonHelper.toJson(info));
            String menuId = (String) info.get("menuId");
            String machineModel = (String) info.get("machineModel");
            if (TextUtils.equals("PCT", machineModel)) {
                machineModel = "";
            }
            SendData.sendUpdateMenuInfo(menuId, machineModel, context, cookingMenuDao);
        } catch (Exception e) {
            log(e.getMessage());
        }
    }

    private void saveFoodMaterial(List<MenuFoodMaterial> data) {
        if (data == null) {
            return;
        }
        for (MenuFoodMaterial foodMaterial : data) {
            foodMaterialDao.addOrUpdate(foodMaterial);
            log("foodMaterial:" + JsonHelper.toJson(foodMaterial));
        }
    }


    /**
     * 接收配菜台推送来的信息
     *
     * @param info
     */
    private void menuCookingInfo(Map<String, Object> info) {
        try {
            log("菜谱内容:" + info);
            CookingMenu cookingMenu = null;
            List<CookingMenu> list = null;
            cookingMenu = cookingMenuDao.queryById((String) info.get("id"));
            if (cookingMenu == null) {
                list = cookingMenuDao.queryForName((String) info.get("name"));
            } else {
                list = new ArrayList<>();
                list.add(cookingMenu);
            }
            if (list != null && !list.isEmpty()) {
                cookingMenu = list.get(0);
            }
            if (cookingMenu != null) {
                List<Operator> tempList = operatorDao.queryForAllByMID(cookingMenu.getId());
                if (tempList == null || tempList.isEmpty()) {
                    sendMsg(0, "设备端菜谱没有炒菜步骤，不能使用该菜谱", (String) info.get("deviceId"));
                    return;
                }
                if (TextUtils.isEmpty(cookingMenu.getParam1())) {
                    sendMsg(0, "设备端菜谱炒菜参数为空，请先配置餐谱参数", (String) info.get("deviceId"));
                    return;
                }
                cookingMenu.setSpecification((String) info.get("size"));
                log("cookingPage:" + cookingPage + " isCooking:" +
                        isCooking + " cookingMenu:" + JsonHelper.toJson(cookingMenu));
                if (!cookingPage) {
                    sendMsg(0, "目标机器已接收到，请开始炒菜", (String) info.get("deviceId"));
                    gotoOtherActivity(cookingMenu);
                } else {
                    sendMsg(0, "目标机器已接收到，等待炒菜", (String) info.get("deviceId"));
                    saveCacheMenu(cookingMenu);
                }
            } else {
                sendMsg(0, "该机器没有对应的菜谱，请选其他机器", (String) info.get("deviceId"));
            }
        } catch (Exception e) {
            sendMsg(0, "发送的数据有误，请检查数据合法性", (String) info.get("deviceId"));
            log(e.getMessage());
        }
    }

    private void saveCacheMenu(CookingMenu cookingMenu) {
        log("接收推送来的菜谱:" + JsonHelper.toJson(cookingMenu));
        cacheMenus.put(cookingMenu.getName() + "_" + cookingMenu.getSpecification(), cookingMenu);
        EventBus.getDefault().post(cacheMenus.size(), Constant.SHOW_MENU_SIZE);
    }

    public void removeMenuInfo(String key) {
        if (cacheMenus.containsKey(key)) {
            cacheMenus.remove(key);
            EventBus.getDefault().post(cacheMenus.size(), Constant.SHOW_MENU_SIZE);
            log("移除菜谱:" + key);
        } else {
            log("移除菜谱不存在:" + key);
        }
    }

    public List<CookingMenu> getCacheMenus() {
        return new ArrayList<>(cacheMenus.values());
    }

    /**
     * 跳转炒菜界面
     *
     * @param cookingMenu
     */
    private void gotoOtherActivity(CookingMenu cookingMenu) {
        try {
            if (isCooking) {
                EventBus.getDefault().post(cookingMenu, CookingActivity.EVENT_MENU_INFO);
                return;
            }
            Intent intent1 = new Intent(context, CookingActivity.class);
            intent1.putExtra("cookingMenu", JsonHelper.toJson(cookingMenu));
            intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent1.putExtra("operators", "operators");
            context.startActivity(intent1);
        } catch (Exception e) {
            log(e.getMessage());
        }
    }

    /**
     * 推送到设备端
     *
     * @param msg
     * @param deviceId
     */
    private void sendMsg(int option, Object msg, String deviceId) {
        log("推送到设备端：" + msg);
        Map<String, Object> info = new HashMap<>();
        info.put("option", option);
        info.put("data", msg);
        SendData.sendSocketInfo(info, deviceId);
    }

    private void showMsg(String msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    private void log(String msg) {
        Log.e(TAG, msg);
    }


    private CookingMenu getCookingMenu(String name, String size) {
        CookingMenu cookingMenu = new CookingMenu();
        cookingMenu.setName(name);
        cookingMenu.setSpecification(size);
        return cookingMenu;
    }

    public void queryData() {
        getDevices(20);
        getDevices(11);
    }

    /**
     *
     * @param type
     */
    private void getDevices(int type) {
        HashMap<String, Object> params = new HashMap();
        params.put("deviceId", APPDidUtil.getAppDid());
        params.put("type", type);
        OkHttpManager.HttpPostJson(HttpApi.GETDEVICES, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                log("getDevices getDevices=" + e.getMessage());
            }

            @Override
            public void onResponse(String info, int i) {
                try {
                    log("getDevices onResponse=" + info);
                    QueryMsgInfo queryMsgInfo = JsonHelper.parserJson(info, new TypeReference<QueryMsgInfo<DeviceInfo>>() {
                    });
                    if (queryMsgInfo != null) {
                        if (queryMsgInfo.getData() != null && !queryMsgInfo.getData().isEmpty()) {
                            List<DeviceInfo> list = queryMsgInfo.getData();
                            for (DeviceInfo deviceInfo : list) {
                                if (deviceInfo.getType() == 11) {
                                    deviceInfo.setModel("PCT");
                                }
                                devicesMap.put(deviceInfo.getDeviceId(), deviceInfo);
                            }
                        }
                    }
                } catch (Exception e) {

                }
            }
        });
    }

    private String stringQuchong(String id) {
        if (id.contains("_")) {
            return id.substring(0, id.indexOf("_"));
        }
        return id;
    }

    /**
     * 通知餐厅下的炒菜机和配菜台更新菜谱数据
     *
     * @param menuId
     * @param model
     */
    public void pushMenuDataToOtherDevice(String menuId, String model) {
        if (TextUtils.isEmpty(menuId) || devicesMap.isEmpty()) {
            return;
        }
        for (String deviceId : devicesMap.keySet()) {
            if (TextUtils.equals(bJDeviceId, deviceId)) {
                continue;
            }
            DeviceInfo deviceInfo = devicesMap.get(deviceId);
            Map<String, Object> p = new HashMap<>();
            p.put("machineModel", model);
            if (deviceInfo.getType() == 11) {
                p.put("machineModel", "");
                p.put("menuId", menuId);
                sendMsg(13, p, deviceId);
            } else if (deviceInfo.getType() == 20 && TextUtils.equals(model, deviceInfo.getModel())) {
                p.put("machineModel", model);
                p.put("menuId", menuId);
                sendMsg(13, p, deviceId);
            }
        }
    }

    public void pickNextCookingMenu(){

    }
}
